<?php if (!defined("BASEPATH")) exit("No direct script access allowed");

class Login extends MY_Controller {

	function __construct() {
		parent::__construct();
	}

	function index() {
		$response = array();
		if($this->input->post("usrPassword") and $this->input->post("usrEmail")) {
			$this->load->model("user");
			$getUser = $this->user->getUser("usr_email = '".$this->db->escape_str($this->input->post("usrEmail"))."' and usr_password = '".md5($this->input->post("usrPassword"))."' and usr_verify is null");
			if($getUser) {
				$getUser = current($getUser);
				$this->session->set_userdata("usrId", $getUser["usrId"]);
				$this->session->set_userdata("usrEmail", $getUser["usrEmail"]);
				$this->session->set_userdata("usrNewsletter", $getUser["usrNewsletter"]);
				$this->session->set_userdata("grpName", $getUser["grpName"]);
				$this->session->set_userdata("usrProvider", $getUser["usrProvider"]);
				$this->session->set_userdata("fullName", $getUser["fullName"]);
				$this->user->update($getUser["usrId"], array("usr_logged" => $getUser["usrLogged"]+1));

				if($this->input->post("input_rememberme")) {
					$this->load->helper("cookie");
					set_cookie(array("name" => "usrEmail", "value" => $getUser["usrEmail"], "expire" => 60*60*24*30, "path" => "/"));
					set_cookie(array("name" => "usrPassword", "value" => md5($this->input->post("usrPassword")), "expire" => 60*60*24*30, "path" => "/"));
				}

				/*$favourites = $this->session->userdata("favourites");
				if(is_array($favourites)) {
					$this->session->set_flashdata("info", "Your ".anchor("favourites", "favourite list")." was successfully updated!");
					$this->load->model("ent2usr");
					$getEnt2usr = $this->ent2usr->getEnt2usr($where = "e2u_usr_id = '".$this->session->userdata("usrId")."'");
					foreach($favourites as $ENTITY => $entData) {
						foreach($entData as $entId => $ent) {
							if(!isset($getEnt2usr[$ENTITY]) or !isset($getEnt2usr[$ENTITY][$entId])) {
								$this->ent2usr->insert(array("e2u_entity" => $ENTITY, "e2u_ent_id" => $entId, "e2u_text" => $ent["e2uText"], "e2u_usr_id" => $this->session->userdata("usrId")));
							}
						}
					}
				}*/

				$response["success"] = TRUE;
			}
		}
		if($this->input->is_ajax_request()) {
			echo	json_encode($response);
		} else {
			// post controller hook meghivasa redirect elott
			require APPPATH . 'hooks/Daemon_hooks.php'; $hook = new Daemon_hooks(); $hook->call_daemon();
			redirect($this->input->post("redirect", ""));
		}
	}

}